import pygame
import os
import time

class Image(pygame.sprite.Sprite):

    # 初始化
    def __init__(self,path,size,pos) :
        super().__init__()
        self.path = path
        self.size = size
        self.pos = [pos[0],pos[1]]
        self.fileIndex = 0
        self.setFileNum()
        self.updateImage()
        self.time = time.time()

    def setFileNum(self):
        self.fileNum = 0
        if '{}' in self.path :
            self.fileNum = len(os.listdir(self.path[:self.path.rfind('/')]))

    # 加载图片
    def updateImage(self) :
        path = self.path
        if self.fileNum != 0 :
            path = path.format(self.fileIndex)
        self.image = pygame.image.load(path) #加载图片
        self.image = pygame.transform.scale(self.image,self.size) #缩放到宽高

    # 切换图片下标
    def updateFileIndex(self,gap) :
        current_time = time.time()
        if current_time - self.time > gap:
            self.time = current_time
            self.fileIndex = self.fileIndex + 1
            if self.fileIndex == self.fileNum -1:
                self.fileIndex = 0
            self.updateImage()


    #水平移动
    def moveX(self,x) :
        self.pos[0] = self.pos[0] + x

    #垂直移动
    def moveY(self,y) :
        self.pos[1] = self.pos[1] + y

    #获取图片的坐标
    def getRect(self):
        rect = self.image.get_rect()
        rect.x,rect.y = self.pos
        return rect

    # 渲染图片
    def draw(self,surface) :
        surface.blit(self.image,self.getRect())